//
//  BCImageEditorViewController.m
//  图片编辑
//
//  Created by aaaa on 2020/3/30.
//  Copyright © 2020 aaaa. All rights reserved.
//

#import "BCImageEditorViewController.h"
#import "BCImageEditorHelper.h"
#import "BCColorBoard.h"
#import "BCZoomView.h"
#import "BCEditorTextView.h"
#import "BCDeleteZoomView.h"
#import "BCImageEditorDrawView.h"
#import "BCImageEditSqareView.h"
#import "BCImageClipController.h"
static const CGFloat SelcetViewPadding = 20;

typedef enum : NSUInteger {
    BCImageEditPenSize_small = 0,
    BCImageEditPenSize_medium,
    BCImageEditPenSize_large,
} BCImageEditPenSize;

@interface BCImageEditorViewController ()
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
//编辑保存等初级操作
@property (weak, nonatomic) IBOutlet UIStackView *functionStack;
//详细的编辑操作
@property (weak, nonatomic) IBOutlet UIStackView *editStack;
//笔触按钮群
@property (weak, nonatomic) IBOutlet UIStackView *penStrokeStack;
//撤回按钮
@property (weak, nonatomic) IBOutlet UIButton *backwardBtn;
//画板
@property (weak, nonatomic) IBOutlet UIButton *drawBoardButton;
//画画
@property (weak, nonatomic) IBOutlet UIButton *drawButton;
//imageView
@property(nonatomic,strong) UIImageView *imageView;
//记录添加的view
@property(nonatomic,strong) NSMutableArray *operationArray;
//记录
@property(nonatomic,strong) UIView *currentSelectView;
//颜色
@property(nonatomic,strong) __block UIColor *curretColor;
//编辑状态
@property(nonatomic,assign) BOOL isEditing;
//可缩放视图
@property (nonatomic,strong) BCZoomView *zoomView;
//拖动删除的窗口
@property(nonatomic,strong) BCDeleteZoomView *deleteZoomView;
//颜色板
@property(nonatomic,strong) BCColorBoard *colorBoard;
//线条板
@property(nonatomic,strong) BCImageEditorDrawView *drawView;
//线条板
@property(nonatomic,assign) BCImageEditPenSize penSize;
//原始的图片
@property(nonatomic,strong) UIImage *originImage;
//编辑的图片
@property(nonatomic,strong) UIImage *editedImage;
@end

@implementation BCImageEditorViewController

-(instancetype)initWithImage:(UIImage *)image{
    if (self = [super init]) {
        _originImage = image.copy;
        _editedImage = image.copy;
        NSLog(@"_originImage = %p _editedImage = %p",_originImage,_editedImage);
    }
    return self;
}

- (void)viewDidLoad {
   [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.userInteractionEnabled = YES;
    
    [self initState];
    [self setupUI];
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{}

-(void)viewDidLayoutSubviews{
    [super viewDidLayoutSubviews];
    CGFloat top = 0;
    if (@available(iOS 11,*)) {
        top = self.view.safeAreaInsets.top;
    }
    if (_isEditing) {
        _zoomView.frame = (CGRect){CGPointMake(0, top),CGSizeMake(self.view.frame.size.width, CGRectGetMinY(_editStack.frame) - 10 - top)};
    }else{
        _zoomView.frame = (CGRect){CGPointMake(0, top),CGSizeMake(self.view.frame.size.width, CGRectGetMinY(_functionStack.frame) - 20 - top)};
    }
    if (@available(iOS 11,*)) {
        _deleteZoomView.height = 50 + self.view.safeAreaInsets.bottom;
    }
    _deleteZoomView.bottom = self.view.bottom;
}

-(void)initState{
    _isEditing = NO;
    _curretColor = RGB_COLOR(93, 173, 226);
    _penSize = BCImageEditPenSize_medium;

}

-(void)setupUI{
    [self.view addSubview:self.colorBoard];
        
    _imageView = [[UIImageView alloc] initWithImage:_editedImage];
    CGSize contentSize = [BCImageEditorHelper convertImageSize:_editedImage.size showInSize:[UIScreen mainScreen].bounds.size];
    _imageView.frame = (CGRect){CGPointZero,contentSize};
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTapImageForClearSelectView:)];
    [_imageView addGestureRecognizer:tap];
    
    self.drawView.frame = _imageView.bounds;
    [_imageView addSubview:self.drawView];
    
    _zoomView = [[BCZoomView alloc] initWithFrame:self.view.bounds contentView:_imageView];
    [_zoomView enableDoubleTap:YES withScale:2.0];
    _imageView.userInteractionEnabled = YES;
        
    [self.view addSubview:_zoomView];
    [self.view insertSubview:_zoomView atIndex:0];
    [self.view addSubview:self.deleteZoomView];
}

-(void)setImage:(UIImage *)image{
    _editedImage = image;
    [_drawView clearDrawBoard];
    CGSize contentSize = [BCImageEditorHelper convertImageSize:image.size showInSize:[UIScreen mainScreen].bounds.size];
    _imageView.image = image;
    _imageView.frame = (CGRect){CGPointZero,contentSize};
    [_zoomView layoutSubviews];
}


#pragma mark - 编辑相关 -
//进入编辑模式
-(void)beginImageEditing:(BOOL)editing{
    _isEditing = editing;
    
    [UIView animateWithDuration:0.3 animations:^{
        self.titleLabel.alpha = self->_isEditing;
        self.functionStack.alpha = !self->_isEditing;
        self.editStack.alpha = self->_isEditing;
    } completion:^(BOOL finished) {
        self.functionStack.hidden = self->_isEditing;
        self.editStack.hidden = !self->_isEditing;
        [UIView animateWithDuration:0.3 animations:^{
           [self viewDidLayoutSubviews];
        }];
    }];
}

//刷新双击的label
-(void)refreshTextLabelWithSize:(CGSize)size content:(NSString *)text textColor:(UIColor *)color{
    UILabel *label = (UILabel *)self.currentSelectView.superview;
    CGAffineTransform rotate = label.transform;
    label.transform = CGAffineTransformIdentity;
    CGPoint center = label.center;
    label.size = CGSizeMake(size.width + SelcetViewPadding * 2, size.height + SelcetViewPadding * 2);
    label.text = text;
    label.center = center;
    label.textColor = color;
    label.transform = rotate;
    self.currentSelectView.frame = label.bounds;
}

//添加编辑好的文字
-(void)addTextLabelWithSize:(CGSize)size content:(NSString *)text textColor:(UIColor *)color{
    UILabel *label = [UILabel new];
    label.size = CGSizeMake(size.width + SelcetViewPadding * 2, size.height + SelcetViewPadding * 2);
    label.font = [UIFont systemFontOfSize:25.0];
    label.text = text;
    label.textAlignment = NSTextAlignmentCenter;
    label.textColor = color;
    label.numberOfLines = 0;
    label.userInteractionEnabled = YES;
    label.layer.contentsScale = [UIScreen mainScreen].scale;
    [self.imageView addSubview:label];
    
    CGFloat zoomScale = [self.zoomView zoomScale];
    CGPoint point = [self.zoomView imageCenterInZoomView];
    label.center = CGPointMake(point.x * (1/zoomScale), point.y * (1/zoomScale));
    label.transform = CGAffineTransformMakeScale(1 / zoomScale, 1/zoomScale);
    
    [self addNewOpeationResult:label];
    [self addGestureOnView:label];
}

//改变线条颜色
-(void)didChangeColor:(UIColor *)color{
    _curretColor = color;
    [self.penStrokeStack.arrangedSubviews enumerateObjectsUsingBlock:^(__kindof UIButton * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        obj.tintColor = color;
    }];
    [self.drawView setLineColor:_curretColor];
    _drawButton.tintColor = color;
    _drawBoardButton.tintColor = color;
}

-(void)addSqareView{
    BCImageEditSqareView *sqareView = [[BCImageEditSqareView alloc] initWithFrame:CGRectMake(0, 0, 100, 60)];
    [sqareView addSqareLayerWithColor:_curretColor];
    sqareView.center = [_zoomView imageCenterInZoomView];
    [_imageView addSubview:sqareView];
    [self addGestureOnView:sqareView];
    [self addCurrentSelectedView:sqareView];
    [self addNewOpeationResult:sqareView];
}

//添加新的操作结果 可能是label或者view
-(void)addNewOpeationResult:(id)result{
    [self.operationArray addObject:result];
}

//开始编辑图片
-(void)beginEditText:(NSString * _Nullable)text textColor:(UIColor * _Nullable)color{
    BCEditorTextView *textView = [[BCEditorTextView alloc] initWithFrame:self.view.bounds text:text textColor:color];
    [self.view addSubview:textView];
    @weakify(self)
    textView.didInputText = ^(CGSize size ,NSString * _Nonnull text, UIColor * _Nonnull textColor) {
        @strongify(self)
        if (self.currentSelectView && [self.currentSelectView.superview isKindOfClass:[UILabel class]]) {
            [self refreshTextLabelWithSize:size content:text textColor:textColor];
        }else{
            [self addTextLabelWithSize:size content:text textColor:textColor];
        }
    };
    NSLog(@"文字");
}

//设置当前操作的view
-(void)addCurrentSelectedView:(UIView *)view{
    [self.currentSelectView removeFromSuperview];
    self.currentSelectView.frame = view.bounds;
    [view addSubview:self.currentSelectView];
    [_imageView bringSubviewToFront:view];
}

//清除当前操作的view
-(void)clearCurrentSelectedView{
    if (self.currentSelectView.superview) {
        [self.currentSelectView removeFromSuperview];
    }
}

//删除添加的view
-(void)deleteAddedView{
    UIView *v = self.currentSelectView.superview;
    if (v) {
        [self.operationArray removeObject:v];
        [self.currentSelectView removeFromSuperview];
        [v removeFromSuperview];
        v = nil;
        NSLog(@"视图数量：%d",(int)self.operationArray.count);
    }
}

#pragma mark - gesture -
-(void)addGestureOnView:(UIView *)view{
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onTapView:)];
    tap.numberOfTapsRequired = 1;
    tap.numberOfTouchesRequired = 1;
    [view addGestureRecognizer:tap];
    
    UIPinchGestureRecognizer *pinch = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(onPinchView:)];
    [view addGestureRecognizer:pinch];
    
    UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(onPanView:)];
    [view addGestureRecognizer:pan];
    
    if ([view isKindOfClass:[UILabel class]]) {
        UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(onDoubleTapView:)];
        doubleTap.numberOfTapsRequired = 2;
        doubleTap.numberOfTouchesRequired = 1;
        [tap requireGestureRecognizerToFail:doubleTap];
        [view addGestureRecognizer:doubleTap];
    }
    
    UIRotationGestureRecognizer *rotate = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(onRotateView:)];
    [view addGestureRecognizer:rotate];
}

-(void)onTapImageForClearSelectView:(UITapGestureRecognizer *)tap{
    [self.currentSelectView removeFromSuperview];
}

-(void)onTapView:(UITapGestureRecognizer *)tap{
    if (self.currentSelectView && self.currentSelectView.superview == tap.view) {
        [self clearCurrentSelectedView];
    }else{
        [self addCurrentSelectedView:tap.view];
    }
}

-(void)onPinchView:(UIPinchGestureRecognizer *)pin{
    pin.view.transform = CGAffineTransformScale(pin.view.transform, pin.scale, pin.scale);
    if ([pin.view isKindOfClass:[UILabel class]]) {
        UILabel *label = (UILabel *)pin.view;
        label.layer.contentsScale = [UIScreen mainScreen].scale;
    }
    pin.scale = 1.0;
    
}

-(void)onPanView:(UIPanGestureRecognizer *)pan{
    switch (pan.state) {
        case UIGestureRecognizerStateBegan:
            [self addCurrentSelectedView:pan.view];
            break;
        case UIGestureRecognizerStateChanged:{
            CGPoint point = [pan translationInView:_imageView];
            pan.view.center = CGPointMake(pan.view.center.x + point.x, pan.view.center.y + point.y);
            [pan setTranslation:CGPointZero inView:_imageView];
            [self.deleteZoomView show];
            [self.zoomView allowClipToBounce:NO];
            _imageView.clipsToBounds = NO;
            CGPoint p = [_imageView convertPoint:pan.view.center toView:self.view];
            [_deleteZoomView setInZoom:CGRectContainsPoint(_deleteZoomView.frame, p)];
        }
            break;
        case UIGestureRecognizerStateCancelled:
        case UIGestureRecognizerStateFailed:
        case UIGestureRecognizerStateEnded:{
            
            if (_deleteZoomView.inZoom) {
                [self deleteAddedView];
            }
            
            CGRect imageRect = [_imageView convertRect:_imageView.frame toView:self.view];
            CGRect viewRect = [_imageView convertRect:pan.view.frame toView:_imageView];
            NSLog(@"image rect = %@ viewRect = %@",NSStringFromCGRect(imageRect),
                  NSStringFromCGRect(viewRect));
            if (viewRect.origin.y > imageRect.size.height) {
                pan.view.center = [_zoomView imageCenterInZoomView];
            }
            
            [self.deleteZoomView disappear];
            _imageView.clipsToBounds = YES;
            [self.zoomView allowClipToBounce:YES];
            
            [_deleteZoomView setInZoom:NO];
        }
            break;
        default:break;
    }
}

-(void)onRotateView:(UIRotationGestureRecognizer *)rotate{
    if (rotate.state == UIGestureRecognizerStateBegan) {
        [self addGestureOnView:rotate.view];
    }else if (rotate.state == UIGestureRecognizerStateFailed || rotate.state == UIGestureRecognizerStateEnded){
        //应该要移除手势
    }
    rotate.view.transform = CGAffineTransformRotate(rotate.view.transform, rotate.rotation);
    rotate.rotation = 0;
}

-(void)onDoubleTapView:(UIPanGestureRecognizer *)doubleTap{
    if ([doubleTap.view isKindOfClass:[UILabel class]]) {
        UILabel *l = (UILabel *)doubleTap.view;
        [self beginEditText:l.text textColor:l.textColor];
        [self addCurrentSelectedView:l];
    }
}

#pragma mark - user Action -
//改变编辑模式
- (IBAction)changeEditorMode:(UIButton *)sender {
    switch (sender.tag) {
        case 0:{ //画线
            sender.selected = !sender.selected;
        }
            break;
        case 1: {//框框
            NSLog(@"框框");
            _drawButton.selected = NO;
            [self clearCurrentSelectedView];
            [self addSqareView];
        }
            break;
        case 2:{ //文字
            _drawButton.selected = NO;
            [self clearCurrentSelectedView];
            [self beginEditText:@"" textColor:nil];            
        }
            break;
        case 3:{//裁剪
            _drawButton.selected = NO;
            [self clearCurrentSelectedView];
            
            UIImage *image = [_imageView sl_imageByViewInRect:_imageView.bounds];
            BCImageClipController *vc = [BCImageClipController new];
            vc.image = image;
            vc.finishImageClip = ^(UIImage * _Nonnull image) {
                [self setImage:image];
            };
            vc.modalPresentationStyle = UIModalPresentationFullScreen;
            [self presentViewController:vc animated:YES completion:nil];
        }
            break;
    }
    [self becomeDrawable];
}

-(void)becomeDrawable{
    NSLog(@"画线");
    self.drawView.userInteractionEnabled = _drawButton.selected;
}

- (IBAction)goBack:(id)sender {
    //弹窗询问是否要取消编辑
    
    //取消
    _drawButton.selected = NO;
    [self becomeDrawable];
    _editedImage = _originImage.copy;
    _imageView.image = _originImage;
    [self.drawView clearDrawBoard];
    [self.operationArray makeObjectsPerformSelector:@selector(removeFromSuperview)];
    [self.operationArray removeAllObjects];
    [self beginImageEditing:NO];
}

//结束编辑
- (IBAction)finishEditing:(UIButton *)sender {
    NSLog(@"结束编辑");
    [self beginImageEditing:NO];
}

//撤销操作
- (IBAction)withDrawOperation:(UIButton *)sender {
    NSLog(@"撤销操作");
    [self.drawView deleteBackWard];
}

//显示图片面板
- (IBAction)showColorBoard:(UIButton *)sender {
    NSLog(@"颜色板");
    CGPoint point = [self.editStack convertPoint:sender.origin toView:self.view];
    point = CGPointMake(point.x, point.y - 5);
    if ([_colorBoard isShowing]) {
        [_colorBoard disappear];
    }else{
        [_colorBoard showAtPosition:point];
    }
}

//改变线条大小
- (IBAction)changePenSize:(UIButton *)sender {
    NSLog(@"线条粗细选择");
    if (sender.tag != _penSize) {
        _penSize = sender.tag;
        [_penStrokeStack.arrangedSubviews enumerateObjectsUsingBlock:^(__kindof UIButton * _Nonnull btn, NSUInteger idx, BOOL * _Nonnull stop) {
            btn.selected = (btn.tag == _penSize);            
        }];
    }
    [_drawView setLineWidth:[self currentPenSize]];
}

//分享图片
- (IBAction)shareImage:(UIButton *)sender {
    NSLog(@"分享图片");
    
}

//
- (IBAction)editImageOption:(UIButton *)sender {
    switch (sender.tag) {
        case 0://转发
            NSLog(@"转发");
            
            break;
        case 1:
            NSLog(@"保存");
            
            break;
        case 2://编辑
            [self beginImageEditing:YES];
            break;
    }
}


#pragma mark - getter -
-(CGFloat)currentPenSize{
    CGFloat penSize = 0;
    switch (_penSize) {
        case BCImageEditPenSize_small:
            penSize = 5;
            break;
        case BCImageEditPenSize_medium:
            penSize = 7.5;
            break;
        case BCImageEditPenSize_large:
            penSize = 15;
            break;
    }
    return penSize;
}

-(NSMutableArray *)operationArray{
    if (!_operationArray) {
        _operationArray = @[].mutableCopy;
    }
    return _operationArray;
}

-(UIView *)currentSelectView{
    if (!_currentSelectView) {
        _currentSelectView = [UIView new];
        _currentSelectView.layer.borderWidth = 1.0;
        _currentSelectView.layer.borderColor = RGB_COLOR(56, 172, 255).CGColor;
        _currentSelectView.userInteractionEnabled = NO;
    }
    return _currentSelectView;
}

-(BCDeleteZoomView *)deleteZoomView{
    if (!_deleteZoomView) {
        _deleteZoomView = [[BCDeleteZoomView alloc] initWithFrame:CGRectMake(00, 0, ScreenW, 50)];        
    }
    return _deleteZoomView;
}

-(BCImageEditorDrawView *)drawView{
    if (!_drawView) {
        _drawView = [BCImageEditorDrawView new];
        [_drawView setLineWidth:[self currentPenSize]];
        [_drawView setLineColor:_curretColor];
        @weakify(self)
        _drawView.didFinishDrawing = ^(int numOfLayer) {
            @strongify(self)
            self.backwardBtn.enabled = numOfLayer > 0;
        };
    }
    return _drawView;
}

-(BCColorBoard *)colorBoard{
    if (!_colorBoard) {
        _colorBoard = [BCColorBoard new];
        @weakify(self)
        _colorBoard.didselectColor = ^(UIColor * _Nonnull color) {
            @strongify(self)
            [self didChangeColor:color];
        };
    }
    return _colorBoard;
}

@end
